import { genBootstrap, genMount, genUnmount, genUpdate } from './qiankun/lifecycles';
import { renderClient } from './renderer';
import { createPluginManager } from './core/plugin';
import { ApplyPluginsType } from './core/client/plugin';
import { createHistory } from './core/history';
import { getRoutes } from './core/route';
import reportWebVitals from './reportWebVitals';
import './i18next';
import './index.css';

async function render() {
  const pluginManager = createPluginManager();
  const { routes, routeComponents } = await getRoutes()
  await pluginManager.applyPlugins({
    key: 'patchRoutes',
    type: ApplyPluginsType.event,
    args: {
      routes,
      routeComponents,
    },
  });
  const contextOpts = pluginManager.applyPlugins({
    key: 'modifyContextOpts',
    type: ApplyPluginsType.modify,
    initialValue: {},
  });
  const basename = window.__POWERED_BY_QIANKUN__ ? '/' : '/supgpt-app';
  const historyType = 'browser';
  const history = createHistory({
    type: historyType,
    basename
  })
  return (pluginManager.applyPlugins({
    key: 'render',
    type: ApplyPluginsType.compose,
    initialValue() {
      const context = {
        routes,
        routeComponents,
        pluginManager,
        rootElement: contextOpts.rootElement || document.getElementById('root'),
        history,
        historyType,
        basename,
        callback: contextOpts.callback,
      };
      const modifiedContext = pluginManager.applyPlugins({
        key: 'modifyClientRenderOpts',
        type: ApplyPluginsType.modify,
        initialValue: context,
      });
      return renderClient(modifiedContext);
    },
  }))();
}

render();

export const bootstrap = genBootstrap(render);
export const mount = genMount('root');
export const unmount = genUnmount('root');
export const update = genUpdate();

if (!window.__POWERED_BY_QIANKUN__) {
  bootstrap({}).then(mount);
}

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
